package org.pink7.fileBrowser5;

import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.app.ListActivity;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

class TextFilter implements FilenameFilter {
    public boolean accept(File dir, String name) {
        return (name.endsWith(".txt"));    
    }
}

public class fileBrowser5 extends ListActivity {
	public static final String FILE_PATH = "FILE_PATH";
	//public static final String PRE_FILE_PATH = "PRE_FILE_PATH";
	//public static final String NEXT_FILE_PATH = "NEXT_FILE_PATH";
	
	public static final String FILE_NAME = "FILE_NAME";
	//public static final String PRE_FILE_NAME = "PRE_FILE_NAME";
	//public static final String NEXT_FILE_NAME = "NEXT_FILE_NAME";
	private static final String DATA_PATH = new String("/sdcard/");
	private List<String> texts = new ArrayList<String>();
	
	@Override
    public void onCreate(Bundle icicle) {
        try {
        	super.onCreate(icicle);
        	setContentView(R.layout.text_list);
        	updateTextList();
        } catch (NullPointerException e) {
        	Log.v(getString(R.string.app_name), e.getMessage());
        }
    }
    
    public void updateTextList() {
    	
    	try {
    		File home = new File(DATA_PATH);
    		if (home.listFiles( new TextFilter()).length > 0) {
        		for (File file : home.listFiles( new TextFilter())) {
        			texts.add(file.getName());
        		}
    		
        		ArrayAdapter<String> textList = new ArrayAdapter<String>(this,R.layout.text_item,texts);
        		setListAdapter(textList);
    		}
    	} catch(Exception e) {
    		//AlertDialog.show(this, "Alert", message, buttonText, cancelable)
    		texts.add("No SDCard...");
    		ArrayAdapter<String> textList = new ArrayAdapter<String>(this, R.layout.text_item,texts);
    		setListAdapter(textList);
    	}
    	    	
    }
    
	@Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
		// open the clicked Text file.
		super.onListItemClick(l, v, position, id);
		
		
		Intent i = new Intent(this, textViewer.class);
		i.putExtra(FILE_PATH, DATA_PATH + texts.get(position));
		i.putExtra(FILE_NAME, texts.get(position));
		/*if(texts.size()-1 != 0 && position != 0) {
			i.putExtra(PRE_FILE_PATH, DATA_PATH + texts.get(position-1));
			i.putExtra(PRE_FILE_NAME, texts.get(position-1));
		}
		if(texts.size()-1 !=0 && position != texts.size()-1) {
			i.putExtra(NEXT_FILE_PATH, DATA_PATH + texts.get(position+1));
			i.putExtra(NEXT_FILE_NAME, texts.get(position+1));
		}*/
		startSubActivity(i, 0);
			
		 
	}
	
	
}